//
//  MenuController.m
//  owa-notifier
//
//  Created by Sandeep Mistry on 10/07/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "MenuController.h"

#import "OwaClient.h"
#import "Keychain.h"
#import "Preferences.h"

@implementation MenuController

-(void)dealloc
{
	[preferences release];
	[keychain release];
	[updateTimer release];
	[statusItem release];
	[super dealloc];
}

- (void)awakeFromNib
{
	statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength] retain];
	[statusItem setHighlightMode:YES];
	[statusItem setTitle:[NSString stringWithString:@"OWA Notifier"]]; 
	[statusItem setEnabled:YES];
	[statusItem setToolTip:@"Outlook Web Access Notfier"];
	
	[statusItem setMenu:mainMenu];

	[statusItem setTarget:self];
	
	preferences = [[Preferences alloc] init];
	keychain = [[Keychain alloc] init];
	
	[preferences setPollInterval:[NSNumber numberWithInt:1]];

	updateTimer = [[NSTimer scheduledTimerWithTimeInterval:([[preferences pollInterval] intValue] * 60.0) target:self selector:@selector(checkMail:) userInfo:nil repeats:YES] retain];
	[updateTimer fire];
}

-(IBAction)goToInboxAction:(id)sender
{

}

-(IBAction)goComposeMailAction:(id)sender
{
}

-(IBAction)quitAction:(id)sender
{
	[NSApp terminate:self];
}

-(IBAction) checkMail:(id)sender
{
	OwaClient* owaClient = [[OwaClient alloc] initWithHost:[preferences host] username:[keychain username] password:[keychain password]];
	
	[owaClient login];
	
	NSArray* newMail = [owaClient checkInbox];
	
	int numUnread = ((newMail == nil) ? 0 : [newMail count]);
	
	if(numUnread == 0)
	{
		[statusItem setTitle:@"OWA"]; 
	}
	else
	{
		NSString* title = [[[NSString alloc] initWithFormat:@"OWA (%d)", numUnread] autorelease];
		[statusItem setTitle:title];
	}
	
	[owaClient release];
}

@end
